package com.chat.controller.Listener;

import DTO.MQ.DeleteCommentDO;
import com.chat.service.ChatService;
import com.chat.service.RankingRedis;
import constant.RedisPreKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqListener {


    @Autowired
    private ChatService chatService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RankingRedis rankingRedis;

    /**
     * 删除帖子的其他信息
     * @param chatId 帖子id
     * @throws InterruptedException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "chat.delete", durable = "true"),
            exchange = @Exchange(name = "ying.yan.delete", type = ExchangeTypes.FANOUT)
    ))
    public void listenDirectQueue2(Integer chatId) throws InterruptedException {

        log.info("删除帖子id为{}的数据",chatId);
        // 删除收藏数据
        chatService.MQdeleteCollection(chatId);

        // 删除点赞数据
        chatService.MQdeleteLike(chatId);

        // 删除帖子相关图片信息
        chatService.MqdeletePicture(chatId);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "chat.omitComment", durable = "true"),
            exchange = @Exchange(name = "ying.yan.omitComment", type = ExchangeTypes.FANOUT)
    ))
    public void deleteComment(DeleteCommentDO deleteCommentDO) throws InterruptedException {
        log.info("删除帖子id为{}的{}个评论数据",deleteCommentDO.getChatId(),deleteCommentDO.getNumber());

        // 1. 更新数据库中评论数
        chatService.MQupdateComment(deleteCommentDO.getChatId(),deleteCommentDO.getNumber());

        // 2. 删除redis中的数据
        stringRedisTemplate.delete(RedisPreKeyConstant.CHAT_MSG+deleteCommentDO.getChatId());

        // 3. 更新redis中的排行榜数据
        rankingRedis.clCommentChat(deleteCommentDO.getChatId(),deleteCommentDO.getNumber());
    }
}
